package com.inspur.security.cbb3.kms.utils;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;

/**
 * 分页查询参数封装
 * @author lijunchang
 */
@Data
@ApiModel(value="查询条件公共类",description="查询条件传入公共类")
public class PageRequestDate {

    @ApiModelProperty(value = "查询页数，从1开始")
    private Integer page=1;
    @ApiModelProperty(value = "每页条目")
    private Integer limit=1;
    @ApiModelProperty(value = "排序字段，默认为createTime，要求数据库表必须有该字段。")
    private String field;
    @ApiModelProperty(value = "排序方式，asc/desc")
    private String order;

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        if(page>1){
            this.page = page;
        }

    }

    public Integer getLimit() {
        return limit;
    }

    public void setLimit(Integer limit) {
        if(limit>1){
            this.limit = limit;
        }
    }

    /**
     * 封装前台传入的查询分页、排序参数
     * 如果不传排序，默认为createTime desc
     * @return  分页参数
     */
    public Pageable getPageRequest(){
        Sort sort;
        if(!StringUtils.isEmpty(this.field)){
            if(Sort.Direction.ASC.name().equalsIgnoreCase(order)){
                sort= new Sort(Sort.Direction.ASC,this.field.trim());
            }else {
                sort= new Sort(Sort.Direction.DESC,this.field.trim());
            }
        }else {
            sort=new Sort(Sort.Direction.DESC,"createdTime");
        }
        return PageRequest.of(page - 1, limit, sort);
    }

}
